<?php
/**
 * @author 
 */
namespace App\Traits;
use Illuminate\Http\Request;
use App\Repositories\AdminuserRepository;

//登录认证
trait Auth
{

    //是否登录
    public static function isLogin(Request $request){
            if($request->header('token')) {
                $res=self::checkToken($request);
                if(!$res){
                    return false;
                }
                $request->offsetSet('adminId', $res['id']);
                $request->offsetSet('adminName', $res['name']);
                $request->offsetSet('token', $res['token']);
                
                return true;
            }else{
                 return false;
            }

    }
    public static function checkToken(Request $request)
    {
        $token=$request->header('token');
        $userRes=new AdminuserRepository();
        $user=$userRes->infoBytoken($token);
        if($user){
            return self::setToken($user['id']);
        }
        return false;

    }
    public static function setToken($id,$state='')
    {
        $newToken=md5(time().rand(1000,9999));
        $userRes=new AdminuserRepository();
        $userinfo=$userRes->info($id);
        $token='';
        if($userinfo){
            $tc=time()-$userinfo['token_time'];
            if($tc>=86400 || $state=='new'){
                $upArr=[];
                $upArr['login_token']=$newToken;
                $upArr['token_time']=time();
                $upArr['id']=$id;
                $res=$userRes->update($upArr);
                $token= $newToken;
            }else{
                $token= $userinfo['login_token'];
            }
            return ['token'=>$token,'name'=>$userinfo['name'],'id'=>$id];
        }
        return false;
    }
    
    
}